<template>
	<HeaderNav active-index="3"></HeaderNav>
	<TaskContainer>
	  <div class="toolbar">
		<el-button type="primary" @click="handleAdd">
		  <template #icon>
			<el-icon><CirclePlus/></el-icon>
		  </template>
		  添加人员组
		</el-button>
	  </div>
	  <div class="group-cards">
		<el-card v-for="group in list" :key="group.id" class="group-card" shadow="hover">
		  <div class="group-header">
			<h3 class="group-name">{{ group.name }}</h3>
			<span class="group-num">{{ group.num }}人</span>
		  </div>
		  <div class="group-time">
			<el-icon><Timer /></el-icon>
			<span>{{ group.create_time }}</span>
		  </div>
		  <div class="divider"></div>
		  <div class="group-actions">
			<el-button type="info" size="small" @click="handleApply(group)">
			  <template #icon>
				<el-icon><User /></el-icon>
			  </template>
			  添加人员
			</el-button>
			<el-button type="warning" size="small" @click="handleTask(group)">
			  <template #icon>
				<el-icon><Document /></el-icon>
			  </template>
			  分配任务
			</el-button>
			<el-button size="small" @click="handleEdit(group)">
			  <template #icon>
				<el-icon><Edit /></el-icon>
			  </template>
			  编辑
			</el-button>
			<el-button type="danger" size="small" @click="handleDelete(group)">
			  <template #icon>
				<el-icon><Delete /></el-icon>
			  </template>
			  删除
			</el-button>
		  </div>
		</el-card>
	  </div>

    <!-- 分页控件 -->
    <el-pagination
      background
      v-if="totalItems > pageSize"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="totalItems"
      layout="prev, pager, next, jumper"
      @current-change="handlePageChange"
      class="pagination-container"
    />

	</TaskContainer>

	<Footor></Footor>

	<!-- 添加人员组 -->
<el-dialog v-model="showDialog" :title="title" width="450">
	<!-- 添加 success 事件监听 -->
	<GroupAddView v-model:group-name="groupName"
                :group-id="groupId" @success="onAddSuccess" />
	<template #footer>
		<div class="dialog-footer">
			<!-- 这里可以删掉原本的保存按钮，因为 GroupAddView 中已处理保存 -->
			<el-button @click="showDialog = false">关闭</el-button>
		</div>
	</template>
</el-dialog>


	<el-dialog v-model="showDialog2" title="分配人员" width="666" top="10vh">
  <GroupApplyView
    v-model:selectedUsers="selectedUsers"
  />
  <template #footer>
    <div class="dialog-footer">
      <el-button type="primary" @click="handleApplySave">保存</el-button>
      <el-button @click="showDialog2 = false">关闭</el-button>
    </div>
  </template>
</el-dialog>




	<el-dialog v-model="showDialog3" title="分配任务" width="70%" top="10px">
		<GroupTaskListView :group-id="currentGroup.id" v-model="selectedTaskIds"/>
		<template #footer>
		<div class="dialog-footer">
			<el-button type="primary" @click="handleTaskAllot">保存</el-button>
			<el-button @click="showDialog3 = false">关闭</el-button>
		</div>
		</template>
	</el-dialog>



  </template>
  
  <script>
  import HeaderNav from "@/components/HeaderNav.vue"
  import TaskContainer from "@/components/TaskContainer.vue"
  import GroupAddView from "./GroupAddView.vue"
  import GroupApplyView from "./GroupApplyView.vue"
  import GroupTaskListView from "./GroupTaskListView.vue"
  import Footor from '@/components/Footor.vue'


  export default {
	components: {
	  HeaderNav,
	  TaskContainer,
	  GroupAddView,
	  GroupApplyView,
	  GroupTaskListView,
	  Footor,
	},
	data() {
  return {
    showDialog: false,
    showDialog2: false,
    showDialog3: false,
    title: "" ,
    groupName: null,
    list: [] , // ← 清空假数据
    currentPage: 1, // 当前页
    pageSize: 12, // 每页显示的数量
    totalItems: 100, // 总项数
    selectedUsers: [],
    currentGroup: null,
    selectedTaskIds: [],

  }
},
    mounted() {
    console.log("组件挂载成功");
    this.fetchGroups();

  },
	methods: {
     async fetchGroups() {
  try {
    const params = {
      page: this.currentPage,
      page_size: this.pageSize,
    };
    console.log('请求参数:', params);  // 打印请求参数
    const res = await this.$api.getGroupList(params);
     console.log('请求返回的组数据：', res); // 查看返回的数据
    this.list = res.results; // 当前页数据
    this.totalItems = res.count; // 总项数
     // 如果有下一页，更新 nextPage 和 prevPage
    console.log('当前页数据:', this.list);
    console.log('总项数:', this.totalItems);
  } catch (err) {
    console.error('获取组列表失败：', err);
    this.$message.error('加载人员组失败');
  }
},

    // 当分页页码发生变化时调用
    handlePageChange(page) {
      console.log('当前页码:', page);  // 打印当前页码
      this.currentPage = page;
      this.fetchGroups();  // 重新拉取当前页数据
    },

    onAddSuccess() {
    this.showDialog = false;   // 关闭对话框
    this.fetchGroups();        // 重新拉取组列表
    },
	  handleAdd() {
		this.showDialog = true ;
		this.title = "添加人员组" ;
		this.groupName = null ;
	  },

	   async handleApply(group) {
    this.currentGroup = group;
    this.showDialog2 = true;

     try {
  const res = await this.$api.getGroupUsers(group.id);
  console.log('获取的组用户原始数据:', res);
  this.selectedUsers = res
  console.log('当前组已有组员ID:', this.selectedUsers);
} catch (e) {
  this.$message.error("获取组内用户失败");
}
  },

    async handleApplySave() {
       console.log('准备保存的组员ID列表:', this.selectedUsers);
    try {
      await this.$api.updateGroupUsers(this.currentGroup.id, this.selectedUsers);
      this.$message.success("人员保存成功！");
      this.showDialog2 = false;

      // this.currentGroup.num = res.user_count;
    } catch (e) {
      this.$message.error("保存失败");
    }
    this.fetchGroups();
  },

	  handleTask(group) {
      this.showDialog3 = true ;
      // 保存当前选中的组信息
      this.currentGroup = group;
	  },

	  handleEdit(group) {
		this.currentGroup = group;
    this.groupName = group.name;
    this.groupId = group.id;
    this.title = "编辑人员组";
    this.showDialog = true;
	  },

	  async handleDelete(group) {
  this.$layer.confirm("确定要删除该人员组吗?", async index => {
    this.$layer.close(index);
    try {
      await this.$api.deleteGroup(group.id);
      this.$message.success("删除成功");
      this.fetchGroups();
    } catch (error) {
      this.$message.error("删除失败");
    }
  });
},


    async handleTaskAllot() {
      try {
        const groupId = this.currentGroup.id;
        const taskIds = this.selectedTaskIds;

        console.log("请求参数:", {groupId, taskIds}); // 打印参数

        if (!taskIds.length) {
          this.$message.warning("请选择至少一个任务");
          return;
        }

        await this.$api.assignTasksToGroup(groupId, taskIds);

        this.$message.success("任务分配成功");
        this.showDialog3 = false;
      } catch (e) {
        console.error("分配任务失败", e.response?.data || e);
        this.$message.error("任务分配失败");
        console.error(e);
      }
    }
	}
  }
  </script>
  
  <style scoped>
  .toolbar {
	display: flex;
	justify-content: flex-end;
	margin: 20px;
  }
  
  .group-cards {
	display: flex;
	flex-wrap: wrap;
	gap: 20px;
	padding: 0 50px;
  }
  
  .group-card {
	flex: 0 1 calc(25% - 20px);
	box-sizing: border-box;
	transition: transform 0.3s, box-shadow 0.3s;
	background: rgba(255, 255, 255, 0.1);
	border-radius: 12px;
	overflow: hidden;
  }
  
  .group-card:hover {
	transform: translateY(-5px);
	box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
  }
  
  .group-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
	padding: 10px 20px;
	background: rgba(255, 255, 255, 0.05);
	border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  }
  
  .group-name {
	font-size: 16px;
	font-weight: bold;
	color: #ffffff; /* 调整为白色以确保与背景对比 */
  }
  
  .group-num {
	background-color: #f0f0f0;
	padding: 5px 10px;
	border-radius: 12px;
	color: #333;
  }
  
  .group-time {
	display: flex;
	align-items: center;
	margin-bottom: 10px;
	padding: 0 20px;
	color: #888;
  }
  
  .group-time el-icon {
	margin-right: 5px;
  }
  
  .divider {
	height: 1px;
	background-color: #e0e0e0;
	margin: 10px 0;
  }
  
  .group-actions {
	display: flex;
	justify-content: flex-start;
	gap: 5px;
	margin-top: 10px;
	padding: 0 20px 10px;
  }

  /* 在样式部分添加以下内容 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin: 30px 0;
  padding: 0 50px;
  width: 100%;
}
  </style>